package com.xlhl.init.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.xlhl.init.common.Result;
import com.xlhl.init.model.dto.login.AccountLoginDTO;
import com.xlhl.init.model.entity.Account;
import com.xlhl.init.model.entity.RoleAssociationPermission;
import com.xlhl.init.model.vo.login.AccountLoginInfo;
import com.xlhl.init.service.AccountService;
import com.xlhl.init.service.RoleAssociationPermissionService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

/**
 * 登录控制器
 *
 * @author xlhl
 */
@RestController
@RequestMapping("/login")
public class LoginController {

    @Resource
    private AccountService accountService;

    @Resource
    private RoleAssociationPermissionService roleAssociationPermissionService;

    @PostMapping("/account")
    public Result<Void> accountLogin(@RequestBody AccountLoginDTO loginDTO) {
        String username = loginDTO.getUsername();
        String password = loginDTO.getPassword();
        Boolean autoLogin = loginDTO.getAutoLogin();

        Account account = accountService.lambdaQuery()
                .select(Account::getId)
                .eq(Account::getUsername, username)
                .eq(Account::getPassword, password)
                .one();
        StpUtil.login(account.getId(), autoLogin);

        return Result.success();
    }

    @PostMapping("/account/info")
    public Result<AccountLoginInfo> accountInfo() {
        long loginId = StpUtil.getLoginIdAsLong();
        Account account = accountService.lambdaQuery()
                .select(Account::getId, Account::getNickname, Account::getAvatar, Account::getRoleId)
                .eq(Account::getId, loginId)
                .one();

        List<RoleAssociationPermission> permissions = roleAssociationPermissionService.lambdaQuery()
                .select(RoleAssociationPermission::getPermissionMainId, RoleAssociationPermission::getPermission, RoleAssociationPermission::getId)
                .eq(RoleAssociationPermission::getRoleId, account.getRoleId())
                .list();

        AccountLoginInfo loginInfo = new AccountLoginInfo(account);

        //  将权限位图转换为 fatherId: permission 方便前端获取
        HashMap<Long, Long> hash = new HashMap<>(permissions.size());
        for (RoleAssociationPermission permission : permissions) {
            hash.put(permission.getPermissionMainId(), permission.getPermission());
        }
        loginInfo.setPermissions(hash);

        return Result.success(loginInfo);
    }


    @PostMapping("/account/logout")
    public Result<Void> accountLogout() {
        StpUtil.logout();

        return Result.success();
    }
}








